package com.example.qrcode.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.qrcode.entity.GraphicsLibrary;
import com.example.qrcode.mapper.GraphicsLibraryMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/graphicsLibrary")
@RequiredArgsConstructor
public class GraphicsLibraryAdminController {

    private final GraphicsLibraryMapper graphicsLibraryMapper;

    @GetMapping("/test")
    public String test() {
        return "Hello World!GraphicsLibraryAdminController";
    }


    @GetMapping("/page")
    public Page<GraphicsLibrary> page(@RequestParam(defaultValue = "1") long pageNum,
                                      @RequestParam(defaultValue = "10") long pageSize,
                                      @RequestParam(required = false) String graphicName) {
        Page<GraphicsLibrary> page = new Page<>(pageNum, pageSize);
        QueryWrapper<GraphicsLibrary> qw = new QueryWrapper<>();
        if (graphicName != null && !graphicName.isEmpty()) {
            qw.like("graphic_name", graphicName);
        }
        qw.orderByDesc("update_time");
        return graphicsLibraryMapper.selectPage(page, qw);
    }

    @GetMapping("/{id}")
    public Map<String, Object> get(@PathVariable Long id) {
        GraphicsLibrary gl = graphicsLibraryMapper.selectById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("data", gl);
        if (gl != null && gl.getSvg() != null && !gl.getSvg().isEmpty()) {
            try {
                byte[] bytes = Base64.getDecoder().decode(gl.getSvg());
                String svgText = new String(bytes, StandardCharsets.UTF_8);
                map.put("svgText", svgText);
            } catch (Exception ignore) {
                map.put("svgText", "");
            }
        } else {
            map.put("svgText", "");
        }
        return map;
    }

    @PostMapping
    public int create(@RequestBody GraphicsLibrary body) {
        return graphicsLibraryMapper.insert(body);
    }

    @PutMapping
    public int update(@RequestBody GraphicsLibrary body) {
        return graphicsLibraryMapper.updateById(body);
    }

    @DeleteMapping("/{id}")
    public int delete(@PathVariable Long id) {
        return graphicsLibraryMapper.deleteById(id);
    }

    @PostMapping("/batchDelete")
    public int batchDelete(@RequestBody List<Long> ids) {
        return graphicsLibraryMapper.deleteBatchIds(ids);
    }
}

